<template>
  <a-menu
    v-model:selectedKeys="selectedKeys"
    theme="light"
    mode="inline"
    :open-keys="state.openKeys"
    @openChange="onOpenChange"
    @click="handleMenuClick"
  >
    <template v-for="menu in authMenuList" :key="menu.name">
      <!-- 有子菜单的情况 -->
      <a-sub-menu v-if="menu.children?.length" :key="`sub-${menu.name}`">
        <template #icon>
          <component :is="getIconComponent(menu.meta.icon)" />
        </template>
        <template #title>{{ menu.meta.title }}</template>
        <a-menu-item v-for="child in menu.children" :key="child.name">
          {{ child.meta.title }}
        </a-menu-item>
      </a-sub-menu>

      <!-- 没有子菜单的情况 -->
      <a-menu-item v-else :key="menu.name">
        <template #icon>
          <component :is="getIconComponent(menu.meta.icon)" />
        </template>
        {{ menu.meta.title }}
      </a-menu-item>
    </template>
  </a-menu>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';
import * as icons from '@ant-design/icons-vue';
import type { Component } from 'vue';
import type { MenuOptions } from '@/store/interface';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

// 获取菜单数据（确保包含name字段）
authStore.getAuthMenuList();
const authMenuList: MenuOptions[] = authStore.authMenuList;

// 获取图标组件
const getIconComponent = (iconName?: string): Component => {
  if (!iconName) return icons.UserOutlined;
  const IconComponent = icons[iconName as keyof typeof icons];
  return IconComponent || icons.UserOutlined;
};

// 当前选中的菜单项（基于route.name）
const selectedKeys = ref<string[]>([]);

// 子菜单展开状态
const state = reactive({
  rootSubmenuKeys: authMenuList
    .filter((menu) => menu.children?.length)
    .map((menu) => `sub-${menu.name}`), // 基于name生成
  openKeys: [] as string[],
});

// 子菜单展开/折叠变化
const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find((key) => !state.openKeys.includes(key));
  if (!state.rootSubmenuKeys.includes(latestOpenKey || '')) {
    state.openKeys = openKeys;
  } else {
    state.openKeys = latestOpenKey ? [latestOpenKey] : [];
  }
};

// 处理菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  if (!key.startsWith('sub-')) {
    // 使用name进行路由跳转
    router.push({ name: key });
  }
};

// 根据当前路由更新菜单状态
const updateMenuState = () => {
  // 确保 route.name 是字符串
  const routeName = route.name ? String(route.name) : undefined;

  if (routeName) {
    selectedKeys.value = [routeName];

    // 处理父路由
    if (route.matched.length > 1) {
      const parentRoute = route.matched[route.matched.length - 2];
      const parentName = parentRoute?.name
        ? String(parentRoute.name)
        : undefined;

      if (parentName) {
        state.openKeys = [`sub-${parentName}`];
      }
    }
  }
};

// 初始化及监听路由变化
watch(() => route.name, updateMenuState, { immediate: true });
</script>
